package com.kyh.controller.api.sys;

import com.alibaba.fastjson.JSONObject;
import com.kyh.service.UploadService;
import com.kyh.util.qiniucloud.QiniuCloudUtil;
import com.kyh.vo.R;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/api/outer/upload")
public class ApiOuterUploadController {

	private static final Logger logger = Logger.getLogger(ApiOuterUploadController.class);
    @Autowired
    private UploadService uploadService;


    @PostMapping("/getQiniuToken")
    @ResponseBody
    public R getQiniuToken() {
        return uploadService.getQiniuToken();
    }

	@RequestMapping("/uploadfileForEditor")
	public void uploadfileForEditor(Model model, HttpServletRequest request, HttpServletResponse response,
			@RequestParam("fileStream") MultipartFile multipartFile) throws FileUploadException, IOException {

		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		if(!ServletFileUpload.isMultipartContent(request)){
			out.println(getError("请选择文件。"));
			return;
		}

		logger.debug("上传文件");
		logger.debug("上传文件名 ========" + multipartFile.getOriginalFilename());

		/*
		SimpleDateFormat sdfyyyyMMdd = new SimpleDateFormat("/yyyy/MM/dd");
		SimpleDateFormat sdfHHmmssSSS = new SimpleDateFormat("HHmmssSSS");
		Date nowDate = new Date();
		
		// 文件初始名
		String oriFilename = multipartFile.getOriginalFilename();
		
		// .号所在位置
		int lastIndex = oriFilename.lastIndexOf(".");

		// 文件后缀列表
		String imageExts = "gif,jpg,jpeg,png,bmp";
		
		// 扩展名
		String orgFileExt = oriFilename.substring(lastIndex + 1).toLowerCase();

		// 验证扩展名
		if (!imageExts.contains(orgFileExt)) {
			out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + imageExts + "格式。"));
			return;
		}
		
		// 拼接文件名
		String toFilename = sdfHHmmssSSS.format(nowDate) + "." + orgFileExt;
		
		String rootRealPath = System.getProperty("rootRealPath");
		String toRelativePath = "/upload" + sdfyyyyMMdd.format(nowDate);
		String toRealPath = rootRealPath + toRelativePath;
		
		// 创建文件夹
		File toDir = new File(toRealPath + "/");
		if (!toDir.exists()) {
			toDir.mkdirs();
		}

		JSONObject obj = new JSONObject();
		obj.put("error", 0);
		obj.put("url", QiniuProps.get("domain") + toRelativePath + "/" + toFilename);
		
		try {
			InputStream fileInputStream = multipartFile.getInputStream();
			// 将文件保存到本地
			FileOutputStream fs = new FileOutputStream(toRealPath + "/" + toFilename);
			System.out.println("------------" + toRealPath + "/" + toFilename);
			byte[] buffer = new byte[1024 * 1024];
			int bytesum = 0;
			int byteread = 0;
			while ((byteread = fileInputStream.read(buffer)) != -1) {
				bytesum += byteread;
				fs.write(buffer, 0, byteread);
				fs.flush();
			}
			fs.close();
			fileInputStream.close();
			out.println(obj.toJSONString());
			return;
		} catch (IOException e) {
			e.printStackTrace();
			out.println(getError("上传失败"));
			return;
		}
		*/
		
		// 文件初始名
		String sourceFilename = multipartFile.getOriginalFilename();
		
		try {
			InputStream fileInputStream = multipartFile.getInputStream();
			String fileName = new QiniuCloudUtil().upload(fileInputStream, sourceFilename);
			JSONObject obj = new JSONObject();
			obj.put("error", 0);
			obj.put("url", fileName);
			out.println(obj.toJSONString());
			return;
		} catch (Exception e) {
			logger.error(e);
			out.println(getError("上传失败"));
			return;
		}
	}
	

	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}
}
